package com.itheima.service.impl;

import com.itheima.common.AuthThreadLocal;
import com.itheima.common.JwtToken;
import com.itheima.mapper.EmployeeMapper;

import com.itheima.pojo.dto.employeeDto.EmployeeAddDto;
import com.itheima.pojo.dto.employeeDto.EmployeeLoginDto;
import com.itheima.pojo.dto.employeeDto.EmployeeUpdateDto;
import com.itheima.pojo.vo.employeeVo.EmployeeFindByIdVo;
import com.itheima.pojo.vo.employeeVo.EmployeeLoginVo;
import com.itheima.pojo.vo.employeeVo.EmployeePageVo;
import com.itheima.service.EmployeeService;

import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;


import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author tcotk
 */
@Service
public class EmployeeServiceImpl implements EmployeeService {

    @Resource
    public EmployeeMapper employeeMapper;


    @Override
    public EmployeeLoginVo login(EmployeeLoginDto employeeLoginDto){
        //查询用户输入的账号密码是否正确
        String username = employeeLoginDto.getUsername();
        String password = employeeLoginDto.getPassword();
        //生成token返回给前端
        Map<String,Object>map=new HashMap<>();
        map.put("token", username);
        String token = JwtToken.jwt(map);

        EmployeeLoginVo employeeLoginVo = employeeMapper.selectByUsername(username);

        //对比用户账号密码是否正确
        if( employeeLoginVo.getPassword().equals(password)){
            //给密码进行加密
            String newPassword = DigestUtils.md5DigestAsHex(password.getBytes());
            employeeLoginVo.setPassword(newPassword);
            employeeLoginVo.setToken(token);
            //将新的用户信息返还给前端
            return employeeLoginVo;
        }
        return null;
    }



    @Override
    public boolean add(EmployeeAddDto employeeAddDto) {
        String token=AuthThreadLocal.getAuth();
        employeeAddDto.setCreateUser(JwtToken.parse(token));
        employeeAddDto.setCreateTime(LocalDateTime.now());

        int insert = employeeMapper.add(employeeAddDto);
        return insert>0;
    }

    @Override
    public boolean update(EmployeeUpdateDto employeeUpdateDto) {
        employeeUpdateDto.setUpdateTime(LocalDateTime.now());
        employeeUpdateDto.setUpdateUser(JwtToken.parse(AuthThreadLocal.getAuth()));
        return employeeMapper.update(employeeUpdateDto) > 0;
    }

    @Override
    public EmployeeFindByIdVo selectById(String id) {
        return employeeMapper.selectById(id);
    }

    @Override
    public List<EmployeePageVo> selectByPage(int page, int pageSize, String name) {
        page=(page-1)*pageSize;

        return employeeMapper.selectByPage(page, pageSize,name);
    }
}
